#include "EpilLocalFunctionStatementParser.h"
#include "EpilParserException.h"
#include "EpilFunctionBodyParser.h"
#include "EpilPointerHelper.h"


EpilLocalFunctionStatementParser::EpilLocalFunctionStatementParser( EpilTokenStream & tokens )
: EpilSyntaxParserBase( tokens )
{
}


void EpilLocalFunctionStatementParser::Parse()
{
	// localfun -> LOCAL FUNCTION NAME body
	m_statement = new EpilLocalFunctionStatementCode( this->GetTokens().GetPreviousToken( 2 ).location );

	// NAME
	if( this->GetTokens().GetCurrentToken().type != ETT_Identifier )
	{
		EpilPointerHelper::SafeDelete( m_statement );
		throw EpilParserException( t("Identifier expected."), this->GetTokens().GetCurrentToken().location );
	}
	m_statement->SetName( this->GetTokens().GetCurrentToken().text );
	this->GetTokens().MoveToNext();

	// body
	EpilFunctionBodyParser funcBodyParser( this->GetTokens() );
	try
	{
		funcBodyParser.Parse();
	}
	catch( ... )
	{
		EpilPointerHelper::SafeDelete( m_statement );
		throw;
	}
	m_statement->SetBody( funcBodyParser.GetBody() );
}